package com.lottery.material.controller.portal.article;

import com.lottery.material.common.JsonResult;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.dto.portal.article.ArticleInfoDto;
import com.lottery.material.entity.article.ArticleInfo;
import com.lottery.material.entity.circle.CircleInfo;
import com.lottery.material.entity.circle.CircleMemberInfo;
import com.lottery.material.entity.conf.MenuLevelConfig;
import com.lottery.material.entity.portaluser.PortalUserInfo;
import com.lottery.material.service.portal.article.ArticleInfoService;
import com.lottery.material.service.portal.circle.CircleInfoService;
import com.lottery.material.service.portal.circle.CircleMemberInfoService;
import com.lottery.material.service.portal.menuLevel.MenuLevelConfigService;
import com.lottery.material.service.portal.portaluser.PortalUserInfoService;
import com.lottery.material.utils.CalendarUtil;
import com.lottery.material.utils.EmptyUtil;
import com.lottery.material.vo.BaseBody;
import com.lottery.material.vo.article.ArticleInfoVo;
import com.lottery.material.vo.article.CheckArticleVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * @Author:houjie
 * @Description: 发帖相关接口类
 * @Date:Create in 2019/4/8 14:01
 */
@Api(value = "发帖相关接口", tags = { "发帖相关接口" })
@Controller
@RequestMapping("/portal/article")
@Slf4j
public class ArticlePostController extends BaseController {

    @Autowired
    PortalUserInfoService portalUserInfoService;
    @Autowired
    CircleMemberInfoService circleMemberInfoService;
    @Autowired
    CircleInfoService circleInfoService;
    @Autowired
    ArticleInfoService articleInfoService;
    @Autowired
    MenuLevelConfigService menuLevelConfigService;
    @Autowired
    HttpServletRequest request;

    /**
     * @Author: houjie
     * @Description: 验证用户的发帖权限
     * @Date: 2019/4/8 14:47
     */
    @ApiOperation(value="发帖验证", notes="用户发帖权限验证")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "circleId", value = "圈子id", required = true, dataType = "String")
    })
    @PostMapping("/checkArticleAuth")
    @ResponseBody
    public JsonResult checkArticleAuth(@Valid CheckArticleVo baseBody){
        //根据用户userId及圈子circleId获取圈成员信息
        CircleMemberInfo circleMemberInfo = circleMemberInfoService.findByUserIdAndCircleId(baseBody.getUserId(),baseBody.getCircleId());
        if(EmptyUtil.isNotEmpty(circleMemberInfo)){
            return JsonResult.failure(400,"您还未关注过该圈子，不能在该圈内发帖！");
        }
        //判断圈成员是否被禁言
        if(circleMemberInfo.getIsBan()==2){//被禁言
            return JsonResult.failure(400,"您已被圈主禁言，无权在该圈内发帖");
        }
        //根据圈子id查询圈子信息
        CircleInfo circleInfo = circleInfoService.findById(Integer.valueOf(baseBody.getCircleId()));
        List<ArticleInfo> articleInfoList = articleInfoService.findTheDayByUserIdAndCircleId(baseBody.getUserId(),baseBody.getCircleId(), CalendarUtil.getNowDate("yyyy-MM-dd")+" 00:00:00");
        //判断用户发帖时间是否已经满足时间间隔
        if(EmptyUtil.isNotEmpty(articleInfoList)){
            ArticleInfo articleInfo=articleInfoList.get(0);
            if(CalendarUtil.interval(articleInfo.getCreateTime().getTime())<circleInfo.getSendInterval()){//发帖间隔小于发帖时间间隔
                return JsonResult.failure(400,"您刚刚发过一篇文章咯，休息一下再来发帖吧！");
            }
        }
        //判断该成员等级
        if(circleMemberInfo.getRank()==1){//非正式圈员
            if(EmptyUtil.isNotEmpty(articleInfoList) && articleInfoList.size()>=circleInfo.getSendArticleTotal()){
                return JsonResult.failure(400,"您今天的发帖数已达上限，加入圈子发帖不受限制！");
            }
        }
        if(circleMemberInfo.getRank()<=3 && circleInfo.getIsProhibitionPublish()==2){//非圈主全体禁言
                return JsonResult.failure(400,"该圈子当前已被禁言！");
        }
        //查询该圈子的一级分类及二级分类
        MenuLevelConfig menuLevel1 = menuLevelConfigService.findByMenuCode(circleInfo.getMainTypeCode());
        MenuLevelConfig menuLevel2 = menuLevelConfigService.findByMenuCode(circleInfo.getSubTypeCode());
        ArticleInfoDto result = new ArticleInfoDto();
        result.setCircleId(baseBody.getCircleId());
        result.setCircleRank(circleMemberInfo.getRank()+"");
        result.setCircleTypeCode(menuLevel2.getMenuCode());
        result.setCircleTypeName(menuLevel2.getMenuName());
        result.setIsSetHot(menuLevel1.getIsSetHot()+"");
        if("MZQ10001".equals(menuLevel1.getMenuCode()) || "MLQ10001".equals(menuLevel1.getMenuCode())){//足球和篮球
            result.setIsFree("2");
        }else{
            result.setIsFree("1");
        }
        return JsonResult.success("可以发帖",result);
    }


    /**
    * @Author: houjie
    * @Description: 是否可收费验证（用户是否认证）
    * @Date: 2019/4/10 10:57
    */
    @ApiOperation(value="是否可收费验证", notes="收费判断")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
    })
    @PostMapping("/checkIsAuth")
    @ResponseBody
    public JsonResult checkIsAuth(@Valid BaseBody baseBody){
        Optional<PortalUserInfo> portalUserInfo = portalUserInfoService.findByUserId(baseBody.getUserId());
        if(portalUserInfo.get().getIsAuth()==1){//未认证
            return JsonResult.failure(400,"未认证");
        }else{
            return JsonResult.success("已认证");
        }
    }



    /**
     * @Author: houjie
     * @Description: 发帖
     * @Date: 2019/4/8 14:47
     */
    @ApiOperation(value="发帖", notes="用户发帖")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "circleId", value = "圈子id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isHot", value = "是否进入热帖（1：否；2：是）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isEndPublic", value = "比赛结束是否公开（1：否；2：是；）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isCharge", value = "是否收费（1：否；2：是）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "chargeAmount", value = "收费金额", required = false, dataType = "String"),
            @ApiImplicitParam(name = "articleTitle", value = "文章标题", required = false, dataType = "String"),
            @ApiImplicitParam(name = "freeContentSort", value = "免费内容排序规则", required = true, dataType = "String"),
            @ApiImplicitParam(name = "freeArticleContents", value = "免费文章内容", required = true, dataType = "String"),
            @ApiImplicitParam(name = "freeArticleImages", value = "免费文章图片", required = false, dataType = "String"),
            @ApiImplicitParam(name = "freeArticlsCompetitionIds", value = "免费文章赛事id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "paidContentSort", value = "付费内容排序规则", required = false, dataType = "String"),
            @ApiImplicitParam(name = "paidArticleContents", value = "付费文章内容", required = false, dataType = "String"),
            @ApiImplicitParam(name = "paidArticlsCompetitionIds", value = "付费文章赛事id", required = false, dataType = "String")
    })
    @PostMapping("/postArticle" )
    @ResponseBody
    public JsonResult postArticle(@Valid ArticleInfoVo articleInfoVo) throws Exception{
        return JsonResult.success("发帖成功",articleInfoVo);
    }


}
